﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MWRCommunicationLibrary.ARS408
{
    public class Decodor : IDecodor
    {
        /// <summary>
        /// 解析接收到的报文
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public IMWRData DecodeReceiveMsg(byte[] msg)
        {
            if(msg.Length != 13)
            {
                throw new Exception("Msg's Length Not Excepted. Maybe Demaged.");
            }

            int id = this.getDefaultCanID(msg);
            IMWRData data = DataFactory.GenerateDataExam(id);
            data.FillData(getData(msg));
            return data;
        }

        /// <summary>
        /// 获取发送数据包
        /// </summary>
        /// <param name="data"></param>
        /// <param name="radarID"></param>
        /// <returns></returns>
        public byte[] GetSender(IMWRData data, int radarID)
        {
            byte[] msg = data.GetSender(radarID);
            return msg;
        }

        /// <summary>
        /// 获取默认CAN ID （ 去掉雷达编号后ID ）
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        private int getDefaultCanID(byte[] msg)
        {
            return (msg[3] << 8) + (msg[4] & 15);
        }

        /// <summary>
        /// 获取CAN数据帧部分
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        private byte[] getData(byte[] msg)
        {
            return msg.Skip(5).ToArray();
        }
    }
}
